//
//  WBStatuseDAL.m
//  sinaWeibo
//
//  Created by 李江波 on 2016/11/27.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

#import "WBStatuseDAL.h"
#import "WBSQLiteTools.h"
#import "WBOAuthViewModel.h"
#import "LEEHTTPManager.h"

static double expires_date_timeIntravel = - 24 * 60 * 60;
@implementation WBStatuseDAL

//首页加载的数据的迁移
-(void)loadHomeData:(NSString *)sinceID max_id:(NSString *)max_id finished:(void (^)(NSArray<NSDictionary *> *))finshed{

    //就让他开始启动的时候加载一次。。！！！
    if ([max_id isEqualToString:@(1).description] && [sinceID isEqualToString:@(0).description]) {
        
        NSArray<NSDictionary *> *array = [self checkoutStatus:sinceID max_id:max_id];
        if (array.count > 0) {
            //有缓存数据  返回缓存数据
            finshed(array);
            return;
        }
    }
    
    
    
    //没有缓存数据, 请求网络数据
    NSString *urlStr = @"https://api.weibo.com/2/statuses/home_timeline.json";
    NSString *access_token = [WBOAuthViewModel shared].userModel.access_token;
    
    NSDictionary* dict = @{@"access_token" : access_token,
             @"max_id" : max_id,
             @"since_id" : sinceID};
    
    [[LEEHTTPManager share] request:GET UrlString:urlStr parameters:dict finshed:^(NSDictionary *responseObject, NSError *error) {
        
        if (error != nil) {
            
            //block传出去false
            finshed(0);
            return ;
        }
        
        //        NSLog(@"%@",responseObject);
        NSArray *statuses = responseObject[@"statuses"];
        
        finshed(statuses);
        
        [self cacheStatuses:statuses];
    }];
}



//1.检查本地是否有缓存数据
-(NSArray<NSDictionary *> *)checkoutStatus:(NSString *)sinceID max_id:(NSString *)max_id{

    NSString *uid = [WBOAuthViewModel shared].userModel.uid;
    if (uid == nil) {
        
        return nil;
    }
    //会将数据库中所有的缓存数据都查找到
    NSString *sql = [NSString stringWithFormat:@"SELECT statuse FROM T_Statuses WHERE userID = %@ ",uid];
    if (sinceID.integerValue > 0) {
        
        [sql stringByAppendingString:[NSString stringWithFormat:@"AND weiboID > %zd ",sinceID.integerValue]];
    }
    if (max_id.integerValue > 0) {
        
        [sql stringByAppendingString:[NSString stringWithFormat:@"AND weiboID < %zd ",max_id.integerValue]];
    }
    //降序
    sql = [sql stringByAppendingString:@"ORDER BY weiboID DESC "];
    //限制条数
    sql = [sql stringByAppendingString:@"LIMIT 30"];
    
    NSMutableArray *arrayM = [NSMutableArray array];
    
    [[WBSQLiteTools shared].queue inDatabase:^(FMDatabase *db) {
       
        FMResultSet *results = [db executeQuery:sql];
        //逐条获取数据
        while (results.next) {
            
            NSData *data = [results dataForColumn:@"statuse"];
            
             NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            [arrayM addObject:array];
        }
        
    }];
    
    return arrayM;
}


//2. 如果本地有缓存数据 就直接返回本地的缓存数据,给用户节省流量,让用户在没有网络的情况可以浏览之前的内容

//3. 没有缓存数据就请求网络数据 返回网络数据



//4. 获取网络数据之后就应该立即存储网络数据
-(void)cacheStatuses:(NSArray<NSDictionary *>*)array {

    //获取userId
    NSString *uid = [WBOAuthViewModel shared].userModel.uid;
    if (uid == nil) {
        NSLog(@"用户没有登录");
        return;
    }
    
    //如果在对应的主键下已经存在数据 就执行替换的操作
//    NSString *sql = @"INSERT OR REPLACE INTO T_Statuses (weiboID,statuse,userID) VALUES (?,?,?)";
    
    [[WBSQLiteTools shared].queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
       
        for (NSDictionary *dict in array) {
            
            NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];

            BOOL res = [db executeUpdate:@"INSERT OR REPLACE INTO T_Statuses (weiboID,statuse,userID) VALUES (?,?,?)",dict[@"id"],data,uid];
            
            if (res) {
                NSLog(@"插入成功");
            }else{
            
                NSLog(@"插入失败");
                *rollback = YES;
            }
        }
        
    }];
    
}

-(void)deleteCacheStatuses{

    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:expires_date_timeIntravel];
    
//    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    NSString *str = [formatter stringFromDate:date];
    
    [[WBSQLiteTools shared].queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
       
        BOOL res = [db executeUpdate:@"DELETE FROM T_Statuses WHERE create_date < ?" ,str];
        
        if (res) {
            NSLog(@"删除成功");
        }else{
        
            NSLog(@"删除失败");
            *rollback = YES;
        }
    }];
    
}



@end
